<template>
  <div v-loading="loading">
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
        <!-- <a-button>
                    导出模板
                </a-button>
                <a-button>
                    导入
                </a-button> -->
      </template>
      <excel
        ref="exportSelect"
        file-name="处置明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="处置明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['estSize','estUnitPrice','amount','disposalReason']"
        :slot="col"
        slot-scope="text, record"
      >
        <div :key="col">
          <template v-if="record.editable">
            <BaseInput
              v-if="col === 'disposalReason'"
              :value="text"
              @blur="e => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estSize' "
              :precision="3"
              :value="text"
              :disabled="col === 'amount'"
              @change="e => handleChange(e, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estUnitPrice' || col === 'amount'"
              :precision="2"
              :value="text"
              :disabled="col === 'amount'"
              @change="e => handleChange(e, record.id, col)"
            />
            <BaseInputNumber
              v-else
              :precision="2"
              :value="text"
              :disabled="col === 'amount'"
              @change="e => handleChange(e, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record"
      >
        <div class="editable-row-operations">
          <span v-if="record.editable && state !== 3">
            <a @click="() => save(record.id)">保存</a>
            <a @click="cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingKey !== ''"
              @click="() => edit(record.id)"
            >编辑</a>
          </span>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <material-list
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    disposalDetailList,
    disposalDetailDel,
    disposalDetailAdd,
    disposalDetailEdit
} from '@/api/material/assets/disposal'
import { columns } from './insideModel'

const data = []
export default {
	name:'a'+Date.now(),
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            totalSize: 0,
            selectedRowKeys: [],
            columns: columns,
            editingKey: '',
            data: [],
            selectedId: [],
            rules: {
                estSize: [
                    { rule: 'required', message: '暂估数量不能为空' }
                ],
                estUnitPrice: [
                    { rule: 'required', message: '暂估单价不能为空' }
                ]
            }
        }
    },
    mounted: function() {
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        exportSelect: function() {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function() {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        openDailog: function() {
            if (this.editingKey !== '') {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        createList: function(selectRow) {
            let _this = this
            let params = {
                materialName: selectRow.name,
                materialCode: selectRow.code,
                materialModel: selectRow.specificationModel,
                materialUnit: selectRow.unit,
                estSize: null,
                estUnitPrice: null,
                amount: null,
                disposalReason: '',
                materialId: selectRow.id,
                disposalApplyId: this.id
            }
            disposalDetailAdd(params).then(res => {
                if (res.code === 200) {
                    _this.list()
                }
            })
        },
        // 删除
        handleDel() {
            this.delList(disposalDetailDel, () => {
                this.initTable()
                this.selectedId = []
                this.selectedRowKeys = []
                this.selectedRows = []
                this.editingKey = ''
            }, { ids: this.selectedId })
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            this.loading = true
            let _this = this
            disposalDetailList({
                pageSize: callback ? _this.totalSize : _this.pageSize,
                pageNo: _this.pageNo, disposalApplyId: _this.id
            }).then(res => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.data = res.data
                    _this.totalSize = res.totalSize
                    this.cacheData = res.data.map(item => ({ ...item }))
                }
                this.loading = false
            })
        },
        handleChange(value, key, column) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            if (target) {
                target[column] = value
                target['amount'] = target['estSize'] * target['estUnitPrice']
                if (this.rules[column]) {
                    this.customValidation(value, column)
                }
                this.data = newData
            }
        },
        edit(key) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.mainTermsId = target.mainTermsId
                this.employeeName = target.employeeName
                this.data = newData
            }
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
            this.selectedRowKeys = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        save(key) {
            // 编辑保存
            const newData = [...this.data]
            const newCacheData = [...this.cacheData]
            const target = newData.filter(item => key === item.id)[0]
            for (let key in target) {
                if (this.rules[key]) {
                    this.customValidation(target[key], key)
                }
            }
            for (let i in this.customValidationErr) {
                if (i) {
                    return
                }
            }
            target.baseId = this.id
            this.loading = true
            disposalDetailEdit(target).then(res => {
                if (res.code === 200) {
                    this.$message.success('编辑成功')
                    this.initTable()
                    this.$emit('confirm')
                }
                this.loading = false
            })
            const targetCache = newCacheData.filter(item => key === item.id)[0]
            if (target && targetCache) {
                delete target.editable
                this.data = newData
                Object.assign(targetCache, target)
                this.cacheData = newCacheData
            }
            this.editingKey = ''
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map(i => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        cancel(key) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            this.editingKey = ''
            if (target) {
                if (target.isAdd) {
                    newData.splice(0, 1)
                } else {
                    Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
                    target.editable = false
                    delete target.editable
                }
                this.data = newData
            }
        }
    }
}
</script>
